package com.billdowney.service.impl.system;

import java.util.List;
import java.util.Optional;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.billdowney.dao.system.SystemDirectoryDao;
import com.billdowney.entity.system.SystemDirectory;
import com.billdowney.exception.BizException;
import com.billdowney.service.impl.base.BaseServiceImpl;
import com.billdowney.service.interfaces.system.SystemDirectoryService;
import com.billdowney.util.CommonUtil;
import com.billdowney.entity.system.SystemDirectoryType;
import com.billdowney.entity.base.EntityStatus;

/**
 * @Description: 系统字典目录接口实现
 * @author 超级小富翁 - BillDowney
 * @date 2018年8月28日 下午9:45:35
 */
@Service
public class SystemDirectoryServiceImpl extends BaseServiceImpl<SystemDirectoryDao, SystemDirectory, String>
		implements SystemDirectoryService {

	@Resource(type = SystemDirectoryDao.class)
	@Override
	public void setDao(SystemDirectoryDao dao) {
		super.dao = dao;
	}

	@Override
	public List<SystemDirectory> queryList(String parentId, SystemDirectoryType type) throws Exception {
		CommonUtil.isNotEmpty(type, new BizException(10304));
		if (CommonUtil.isEmpty(parentId)) {
			return dao.getAll(EntityStatus.using.toString(), type.toString());
		} else {
			return dao.getAll(EntityStatus.using.toString(), type.toString(), parentId);
		}
	}

	@Override
	public SystemDirectory findById(String id) throws Exception {
		if (CommonUtil.isEmpty(id)) {
			throw new BizException(10301);
		}
		Optional<SystemDirectory> systemDirectory = dao.findById(id);
		if (systemDirectory.isPresent()) {
			return systemDirectory.get();
		} else {
			throw new BizException(10301);
		}
	}

	@Override
	public SystemDirectory saveOrUpdateSystemDirectory(String name, String id, SystemDirectoryType directoryType,
			String parentId) throws Exception {
		CommonUtil.isNotEmpty(name, new BizException(10305));
		SystemDirectory directory = null;
		if (CommonUtil.isNotEmpty(id)) {
			directory = this.findById(id);
		} else {
			directory = new SystemDirectory();
		}
		directory.setName(name);
		directory.setType(directoryType);
		dao.save(directory);
		dao.updateDirectoryRelation(directory.getId(), parentId);
		return directory;
	}

	@Override
	public boolean delSystemDirectory(String id) throws Exception {
		SystemDirectory directory = this.findById(id);
		if (this.queryList(id, null).size() > 0) {
			throw new BizException(10303);
		}
		dao.delete(directory);
		return true;
	}

}
